#include <stdio.h>
#include <string.h>
#include "cJSON.h"

int main(int argc, char **argv)
{
    cJSON *root;
    cJSON *obj1;
    cJSON *obj2;
    cJSON *obj11;
    cJSON *obj12;
    char *result;               // 创建得到的 JSON 字符串
    int length;                 // 创建得到的 JSON 字符串的长度
    char *name = "test.json";   // 输出的 JSON 文件名
    FILE *fp;                   // 输出的 JSON 文件
    int len;                    // 实际写入文件中的数据长度

    root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "id", 1);
    cJSON_AddStringToObject(root, "name", "ROOT");
    cJSON_AddNumberToObject(root, "val", 100);

    obj1 = cJSON_CreateObject();
    cJSON_AddNumberToObject(obj1, "id", 2);
    cJSON_AddStringToObject(obj1, "name", "OBJ-1");
    cJSON_AddNumberToObject(obj1, "val", 99);

    obj2 = cJSON_CreateObject();
    cJSON_AddNumberToObject(obj2, "id", 3);
    cJSON_AddStringToObject(obj2, "name", "OBJ-2");
    cJSON_AddNumberToObject(obj2, "val", 98);

    obj11 = cJSON_CreateObject();
    cJSON_AddNumberToObject(obj11, "id", 4);
    cJSON_AddStringToObject(obj11, "name", "OBJ-11");
    cJSON_AddNumberToObject(obj11, "val", 97);

    obj12 = cJSON_CreateObject();
    cJSON_AddNumberToObject(obj12, "id", 5);
    cJSON_AddStringToObject(obj12, "name", "OBJ-12");
    cJSON_AddNumberToObject(obj12, "val", 96);

    cJSON_AddItemToObject(root, "obj_1", obj1);
    cJSON_AddItemToObject(root, "obj_2", obj2);
    cJSON_AddItemToObject(obj1, "obj_11", obj11);
    cJSON_AddItemToObject(obj1, "obj_12", obj12);

    result = cJSON_Print(root);
    length = strlen(result);
    // printf("root: \r\n%s\r\n", result);

    cJSON_Delete(root);

    /* 创建输出JSON文件 */
    fp = fopen(name, "wb");
    if (!fp)
    {
        printf("err: open %s file failed!\r\n", name);
        return -1;
    }

    len = fwrite(result, 1, length, fp);
    if(len != length)
    {
        printf("err: %s write failed! len = %d, length = %d\r\n", name, (int)len, length);
        return -1;
    }
    fclose(fp);

    return 0;
}